import { Inject, Injectable } from '@nestjs/common';
import { DbOptions } from './db.module';
import { access, readFile, writeFile } from 'fs/promises';
import { RegisterUserDto } from 'src/user/dto/register-user.dto';

@Injectable()
export class DbService {
  @Inject('OPTIONS')
  private readonly options: DbOptions;
  async read() {
    const filePath = this.options.path;
    try {
      await access(filePath);
    } catch (err) {
      return [];
    }
    const str = await readFile(filePath, {
      encoding: 'utf-8',
    });
    if (str) {
      return JSON.parse(str);
    }
    return [];
  }
  async write(data: Record<string, any>) {
    const filePath = this.options.path;
    await writeFile(filePath, JSON.stringify(data || []));
  }
}
